package cn.lg.soar.system.auth.client;

import cn.lg.soar.common.util.BeanCopier;
import cn.lg.soar.core.annotations.ApiClient;
import cn.lg.soar.system.api.constant.ModuleConst;
import cn.lg.soar.system.api.model.AuthPost;
import cn.lg.soar.system.api.model.PostDTO;
import cn.lg.soar.system.api.service.IPostApi;
import cn.lg.soar.system.auth.entity.Post;
import cn.lg.soar.system.auth.service.IPostService;
import cn.lg.soar.system.auth.service.UserOrgService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author luguoxiang
 * @date 2022/1/3
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
@ApiIgnore
@ApiClient("boot")
@RestController
@RequestMapping(ModuleConst.CLIENT_PATH + "/post")
public class PostApiClient implements IPostApi {

    @Autowired
    private IPostService service;
    @Autowired
    private UserOrgService userOrgService;

    private final static BeanCopier<Post, PostDTO> ENTITY_TO_DTO = BeanCopier.create(Post.class, PostDTO.class);

    @GetMapping("codesByUserId")
    @Override
    public List<Long> idsByUserId(@RequestParam Long userId) {
        return userOrgService.getPostIds(userId);
    }

    @GetMapping("listByIds")
    @Override
    public List<PostDTO> listByIds(@RequestParam List<Long> ids) {
        if (CollectionUtils.isEmpty(ids)) {
            return Collections.emptyList();
        }
        return ENTITY_TO_DTO.convertBatch(service.listByIds(ids)).collect(Collectors.toList());
    }

    @GetMapping("getById")
    @Override
    public PostDTO getById(@RequestParam Long id) {
        return ENTITY_TO_DTO.convertNullable(service.getById(id));
    }

    @GetMapping("listByUserId")
    @Override
    public List<PostDTO> listByUserId(@RequestParam("userId") Long userId) {
        List<Post> list = service.listByUserId(userId);
        return ENTITY_TO_DTO.convertBatch(list).collect(Collectors.toList());
    }

    @GetMapping("userPostList")
    @Override
    public List<AuthPost> userPostList(@RequestParam("userId") Long userId) {
        List<Post> posts = service.listByUserId(userId);
        return posts.stream().map(x -> {
            AuthPost authPost = new AuthPost();
            authPost.setId(x.getId());
            authPost.setName(x.getName());
            authPost.setAlias(x.getAlias());
            authPost.setRemark(x.getRemark());
            return authPost;
        }).collect(Collectors.toList());
    }
}
